﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Core.Common.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static void AddAssembly(this IServiceCollection service, string assemblyName)
        {
            var ass = Assembly.Load(assemblyName);
            // 获取程序集中符合条件的类型（类名以“Service"结尾的非泛型类）
            var types = ass.GetTypes().Where(t => !t.IsGenericType);
            foreach (var item in types)
            {
                // 获取当前类所继承接口，可以获取单个也可以获取所有的
                //var itype = item.GetInterface("I" + item.Name);

                var interfaces = item.GetInterfaces().Where(i => !i.IsGenericType).ToArray();
                if (interfaces.Length > 0)
                {
                    service.AddScoped(interfaces[0], item);
                }
            }
        }
    }
}
